<?php

namespace App\Services;

use Overtrue\EasySms\EasySms;
use App\Exceptions\MyException;

class SmsService
{
    protected $params = [];

    /**
     * @Notes: 核对参数
     *
     * @throws MyException
     * @Author: smile
     * @Date: 2021/4/23
     * @Time: 10:31
     */
    public function checkParams()
    {
        if (!isset($this->params['phone']) || empty($this->params['phone'])){
            throw new MyException('phone not set');
        }

        if (!isset($this->params['allow']) || empty($this->params['allow'])){
            throw new MyException('allow not set');
        }
    }

    /**
     * @Notes: 保存allow
     *
     * @param string $allow
     * @return object
     * @Author: smile
     * @Date: 2021/4/23
     * @Time: 11:38
     */
    public function allow(string $allow) : object
    {
        $this->params['allow'] = $allow;

        return $this;
    }

    /**
     * @Notes: 保存phone
     *
     * @param string $phone
     * @return object
     * @Author: smile
     * @Date: 2021/4/23
     * @Time: 11:38
     */
    public function number(string $phone) : object
    {
        $this->params['phone'] = $phone;

        return $this;
    }

    /**
     * @Notes: 发送短信
     *
     * @param array $content
     * @return array
     * @throws MyException
     * @Author: smile
     * @Date: 2021/4/23
     * @Time: 10:44
     */
    public function send(array $content) : array
    {
        $config = config('sms');

        $this->checkParams();

        if (preg_match("/^[1]([3-9])[0-9]{9}$/",$this->params['phone'])){
            if (!in_array($this->params['allow'],array_keys(config('sms.allows')))){
                return custom_return_success('发送失败，类型'.config('sms.allows')[$this->params['allow']].'不被允许');
            }

            array_unshift($content,config('sms.allows')[$this->params['allow']]);

            try{
                $easySms = new EasySms($config);

                $easySms->send($this->params['phone'], [
                    'template' => config('sms.template_id'),
                    'data'     => $content
                ]);

                return custom_return_success('发送成功');

            }catch (\Exception $exception){
                $result = $exception->getExceptions();

                if (is_array($result) && isset($result['qcloud'])){
                    $message = $result['qcloud']->getMessage();
                } else {
                    $message = '未知错误';
                }

                return custom_return_error($message);
            }
        }

        return custom_return_success('发送失败，手机号格式错误');
    }
}